import time
import json

from services.ReportQueueService import ReportQueueService
from geopy import distance


class InstantComputeService:
	@staticmethod
	def run():
		while True:
			data = ReportQueueService.pop(ReportQueueService.REPORT_FOR_COMPUTE)
			if not data:
				time.sleep(1)
			else:
				try:
					data = json.loads(data)
					last = ReportQueueService.last(data['rfid'])
					print(data)
					if last:
						last = json.loads(last)
					if last and last['reader_id'] != data['reader_id']:
						trip = distance.distance(
							(last['latitude'], last['longitude']),
							(data['latitude'], data['longitude'])).m
						interval = data['timestamp'] - last['timestamp']
						data['velocity'] = trip / interval
						ReportQueueService.publish(ReportQueueService.REPORT_FOR_VELOCITY, json.dumps(data))
					if not last:
						ReportQueueService.publish(ReportQueueService.REPORT_FOR_VELOCITY, json.dumps(data))
					ReportQueueService.set_last(data['rfid'], json.dumps(data))
				except Exception as e:
					raise


if __name__ == '__main__':
	InstantComputeService.run()
